package com.cwj.algorithm.linear;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author chenwujie
 * @date 2020/11/1614:44
 */
public class BracketMatch {
    /**
     * 括号匹配
     * @param str
     * @return
     */
    public static boolean isMatch(String str){
        if(str == null){
            throw new NullPointerException("str is null");
        }
        if(str.isEmpty()){
            return false;
        }
        Deque<Character> stack = new LinkedList<>();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if(c != '(' && c != ')'){
                continue;
            }
            if(stack.isEmpty()){
                if(c == ')'){
                    return false;
                }
                stack.push(c);
            }else{
                Character peek = stack.peek();
                if(c == ')'){
                    stack.pop();
                }else{
                    stack.push(c);
                }
            }

        }
        return stack.isEmpty();
    }
}
